package org.ens.delegation.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.hibernate3.HibernateTemplate;

import org.ens.delegation.bo.IBusinessObject;
import org.ens.delegation.dao.IGenericDao;

public abstract class GenericDao<T extends IBusinessObject<PK>,PK> implements IGenericDao<T, PK>{

    protected final Log log = LogFactory.getLog(getReferencedClass());

    private HibernateTemplate hibernateTemplate;

    @Override
    public void remove(PK pk) {
            hibernateTemplate.delete(getById(pk));
    }

    @Override
    public boolean exists(PK pk) {
            return (getById(pk) != null);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> getAll() {
            return hibernateTemplate.getSessionFactory()
            .getCurrentSession().createCriteria(getReferencedClass()).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> getAll(Order order) {
            return hibernateTemplate.getSessionFactory()
            .getCurrentSession().createCriteria(getReferencedClass()).addOrder(order).list();
    }

    @Override
    public T getById(PK pk) {
            return hibernateTemplate.get(getReferencedClass(), (Serializable) pk);
    }

    @Override
    public T save(T t) {
            return hibernateTemplate.merge(t);
    }


    @Autowired
    @Required
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    public HibernateTemplate getHibernateTemplate() {
            return hibernateTemplate;
    }


}
